package com.itheima.controller;

import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;



    /**
     * @HystrixCommand(fallbackMethod = "findUserFallBack")降级逻辑的备用方法
     * @param username
     * @return
     */
    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "findUserFallBack")
    public User queryById(@PathVariable("id") String username) throws Exception {
//        //方案1.DiscoveryClient解决url地址写死问题
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//
//        String uri = serviceInstance.getUri().toString();
        //请求地址
//        String url = uri + "/user/" + username;
//        System.out.println("url = " + url);


        //方案2：解决负载均衡的问题
//        Thread.sleep(5000);


        System.out.println("1 = " + 1);
        String url = "http://user-service/user/" + username; // user-service 微服务名称
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }



    /**
     * 服务降级方法
     * 熔断开启时的备用方案
     * @param username
     * @return
     */
    public User findUserFallBack(String username){

        System.out.println("===============consumer");
        User user = new User();
        user.setUsername(username);
        user.setName("pause！");
        return user;

    }
}
